const app = getApp();
console.info("app",app);
Page({

  /**
   * 页面的初始数据
   */
  data: {
    xiaoqu:"长沙市开福区人民政府(盛世路北)",
    address:"湖南省长沙市开福区盛世路",
    latitude: 0,
    longitude: 0,
    markers: [{
      id: 1,
      iconPath: "/images/location.png",
      latitude: 0,
      longitude: 0,
      name: '当前位置',
      width: 50,
      height: 50
    }],
    historyShop: [],//历史提货点
    shopList: [], //附近的提货点
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that=this;
    that.mapCtx = wx.createMapContext('myMap');
    // that.getHistory();
    wx.getLocation({
      type: 'gcj02',
      success (res) {
        that.data.longitude=res.longitude;
        that.data.latitude=res.latitude;
        that.data.markers[0].latitude=res.latitude;
        that.data.markers[0].longitude=res.longitude;
        let points = {
          lng: res.longitude,
          lat: res.latitude
        };
        // that.getNearestShop(points);
        that.initBMap(res.latitude,res.longitude);
      }
    })
    setTimeout(()=>{
      that.mapCtx.moveToLocation();
    },2000)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that=this;
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  valueChange(e) {
    this.data.searchKey = e.detail;
  },
  onConfirm(e) {
    let shopId = e.currentTarget.dataset.shopid;
    //店铺信息更新
    this.getbind(shopId);
  },
  onSearch() {
    let that = this;
    let params={
      teamName: that.data.searchKey,
      longitude: that.data.longitude,
      latitude: that.data.latitude,
      limit: 10,
    };
    app.api.shopNearest(params,(response)=>{
      response.data.forEach((item,index,array)=>{
        item.distance=that.getDistance(that.data.latitude, that.data.longitude, item.lat, item.lng).toFixed(2);
      })
      that.setData({
        shopList:response.data
      })
    },(e)=>{
      app.functions.showToast(e.msg);
    })

  },
  // 获取地址
  initBMap(latitude, longitude) {
    let that = this;
    wx.request({
      url:"https://api.map.baidu.com/geocoder/v2/?ak=WUTygmxMNWO2yI8yCtMyGIyCaXlfurHl&location="+latitude+","+longitude+"&output=json",
      data: {},
      header: {
        "Content-Type": "application/json"
      },
      success: function(res) {
        that.setData({
          address:res.data.result.formatted_address,
          xiaoqu:res.data.result.sematic_description
        })
      },
      fail: function(e) {
        app.functions.showToast("定位失败!");
      }
    });
  },
  // 得到历史的提货点
  getHistory() {
    let that = this;
    let user= app.functions.getLocalStorage("user");
    if(app.functions.isEmpty(user)){
      return false;
    }
    app.api.shopRecord({mid:user.id},(response)=>{
      console.info("response",response);
      that.setData({
        historyShop:response.data
      })
    },(error)=>{

    })

  },
  // 就近提货点
  getNearestShop(point) {
    let that = this;
    let params={
      longitude: point.lng,
      latitude: point.lat,
      limit: 10,
    };
    app.api.shopNearest(params,(response)=>{
      response.data.forEach((item,index,array)=>{
        item.distance=that.getDistance(that.data.latitude, that.data.longitude, item.lat, item.lng).toFixed(2);
      })
      that.setData({
        shopList:response.data
      })
    },(e)=>{
      app.functions.showToast(e.msg);
    })

  },
    // 重新定位
    initData() {
      let that = this;
      wx.getSetting({
        success (result) {
          if(result.authSetting['scope.userLocation']==false){
            wx.showModal({
              title: '提示', //提示的标题,
              content: '去授权小程序获取地理位置', //提示的内容,
              showCancel: true, //是否显示取消按钮,
              cancelText: '取消', //取消按钮的文字，默认为取消，最多 4 个字符,
              cancelColor: '#000000', //取消按钮的文字颜色,
              confirmText: '确定', //确定按钮的文字，默认为取消，最多 4 个字符,
              confirmColor: '#3CC51F', //确定按钮的文字颜色,
              success: res => {
                if(res.confirm){
                  wx.openSetting({
                    success (res) {
                      console.log(res.authSetting)
                    }
                  })
                }
              }
            });
          }
        }
      })
      wx.chooseLocation({
          success: function (res) {
            that.setData({
              address:res.address,
              xiaoqu:res.name,
              longitude:res.longitude,
              latitude:res.latitude,
              'markers[0].latitude':res.latitude,
              'markers[0].longitude':res.longitude,
 
            })
            that.mapCtx.moveToLocation();
            let points = {
              lng: res.longitude,
              lat: res.latitude
            };
            that.getNearestShop(points);
          },
          fail: function () {
            app.functions.showToast("需获取定位提供就近提货点");
          },
          complete: function () {
          
          }
      })
    },
    getDistance(lat1, lng1, lat2, lng2) {
      var radLat1 = (lat1 * Math.PI) / 180.0;
      var radLat2 = (lat2 * Math.PI) / 180.0;
      var a = radLat1 - radLat2;
      var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
      var s =
        2 *
        Math.asin(
          Math.sqrt(
            Math.pow(Math.sin(a / 2), 2) +
              Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
          )
        );
      s = s * 6378.137; // EARTH_RADIUS;
      s = Math.round(s * 10000) / 10000;
      return s;
    },
    // 判断是否有绑定登录
    getbind(shopid){
      let user= app.functions.getLocalStorage("user");
      if(app.functions.isEmpty(user)){
        // 没有登录时绑定店铺
        let params={
          shopId: shopid
        };
        app.api.shopMember(params,(response)=>{
          app.functions.setLocalStorage('shop',response.data);
          wx.switchTab({
            url: "/pages/home/home"
          });
          return;
        },(e)=>{
          app.functions.showToast(e.msg);
        })
      }else{
        this.shopBind(shopid);
      }
    },
    // 绑定店铺
    shopBind(shopId){
      let user = app.functions.getLocalStorage("user");
      // if (user.upshopTid == shopId || user.isteam == 3) {
      //   wx.switchTab({
      //       url: "/pages/home/home"
      //     });
      //   return;
      // }
      let params={
          memberId: user.id,
          teamId: shopId
      };
      app.api.shopBInd(params,(response)=>{
        user.upshopTid = shopId;
        user.centreId = response.data;
        app.functions.setLocalStorage("user",user);
        app.api.shopMsg({id: shopId},(res)=>{
          if (res.data) {
            const shop = res.data;
            app.functions.setLocalStorage('shop',shop);
            wx.switchTab({
              url: "/pages/home/home"
            });
          }
    
        },(e)=>{
          app.functions.showToast(e.msg);
        })
      },(e)=>{
        app.functions.showToast(e.msg);
      })

    }
})
